#include <iostream>
#include "CThread.h"
//#include <stdio.h>
using namespace std;

typedef void* (*tc_thread_func)(void*);

void* ThreadRun(CThread* pstThread)
{
	//pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS,NULL);
	pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
	if(pstThread != NULL)
	{
	  pstThread->Run();
	  pstThread->m_bStart = false;
	  pstThread->OnEnd();
  }
	return NULL;
}

CThread::CThread(bool bDetach)
{
  m_bDetach = bDetach;
	m_bStart = false;
	
	pthread_attr_init(&m_tThreadAttr);
	if (m_bDetach)
	{
		//printf("CThread construct!\n");
		pthread_attr_setdetachstate(&m_tThreadAttr, PTHREAD_CREATE_DETACHED);
	}
	else
	{
		pthread_attr_setdetachstate(&m_tThreadAttr, PTHREAD_CREATE_JOINABLE);
	}
}

CThread::~CThread()
{
  pthread_attr_destroy(&m_tThreadAttr);
  OnDelete();
}
	
bool CThread::Start()
{
  if (m_bStart)
	{
		return false;
	}	
	//printf("Start Thread!\n");
	if(false == OnStart())
	{
		return false;
	}
	int iResult = pthread_create(&m_tThread, &m_tThreadAttr, (tc_thread_func)ThreadRun, this);
	if (iResult)
	{
		cout<<"Create thread failure!"<<endl;
		return false;
	}
	cout<<"Create thread threadid="<<m_tThread<<endl;
	m_bStart = true;
	return true;
}


int CThread::Terminate()
{
  if(m_bStart)
  {
    m_bStart = false;
    return pthread_cancel(m_tThread);
  }
  return 0;
}


void CThread::OnDelete()
{
  int iResult;
	
	if (m_bStart && pthread_self() != m_tThread)	
	{
		iResult = pthread_cancel(m_tThread);
		if (iResult)
		{
			return;
		}

		if (!m_bDetach)
		{
			pthread_join(m_tThread, NULL);
		}
	}
}

int CThread::Join()
{
	void *iStatus;
	pthread_join(m_tThread, &iStatus);
	return 0;
}